package com.starblink.brand.widget

import android.app.Activity
import android.view.View
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.starblink.android.basic.ext.bindFragment
import com.starblink.android.basic.ext.toJson
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.widget.dialog.BaseBottomSheetFragment
import com.starblink.basic.log.SKLogger
import com.starblink.basic.style.R
import com.starblink.brand.bean.FilterCategoryBean
import com.starblink.brand.databinding.DialogBrandFilterBinding
import com.starblink.brand.ui.FilterCategoryFragment
import com.starblink.brand.ui.FilterPriceFragment

class BrandFilterDialog(
    val context: Activity,
    private val brandCollectionId:String?,
    private val lowestPrice:Double?,
    private val highestPrice:Double?,
    private val frontCategoryIds:ArrayList<String>?,
    private val ifHavefilterCategory:Boolean,
    private val doFilter: (lowestPrice:Double?, highestPrice:Double?, frontCategoryIds:ArrayList<String>?,ifShowLoading:Boolean) -> Unit)
    : BaseBottomSheetFragment(),FilterDialogI {
    private val TAG = "BrandFilterDialog"
    lateinit var mBinding: DialogBrandFilterBinding
    private val filterCategoryFragment by lazy {FilterCategoryFragment.obtainFragment(brandCollectionId,frontCategoryIds)}
    private val filterPriceFragment by lazy {FilterPriceFragment.obtainFragment(lowestPrice,highestPrice)}
    private val redCircleDrawable =
        ContextCompat.getDrawable(context, R.drawable.bg_rect_circle_red_6dp)
    private var pageChangeSelected=0
    override fun getBindingRootView(): View {
        mBinding = DialogBrandFilterBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initView() {
        filterCategoryFragment.setFilterDialogI(this)
        filterPriceFragment.setFilterData(this)
        val fragmentList: List<Fragment> = listOf(
            filterCategoryFragment,
            filterPriceFragment
        )
        mBinding.vpDialogFilter.bindFragment(
            childFragmentManager,
            fragmentList,
            pageChangeSelected = {
                //处理红点逻辑
                pageChangeSelected=it
                changeRedPointState()
            })
        //界面禁止回收
        mBinding.vpDialogFilter.offscreenPageLimit = fragmentList.size

        mBinding.ivDialogClose.setOnClickListener {
            dismiss()
        }

        mBinding.llCategory.setOnClickListener {
            //分类tab
            changeTab(0)
        }
        mBinding.llPrice.setOnClickListener {
            //价格tab
            changeTab(1)
        }

        mBinding.btnClear.setOnClickListener {
            //清空
            filterCategoryFragment.clearFilterCategoryList()
            filterPriceFragment.clearPriceInput()
            changeRedPointState()
            doFilter.invoke(null,null,null,false)
        }
        mBinding.btnDone.setOnClickListener {
            //Done
            val filterCategoryList=filterCategoryFragment.getFilterCategoryList()
            val filterPriceInputBean=filterPriceFragment.getPriceInput()
            SKLogger.d(TAG, "btnDone --- ${filterPriceInputBean.toJson()} ---${filterCategoryList.toJson()}")
            doFilter.invoke(filterPriceInputBean.min,filterPriceInputBean.max,getFilterCategoryId(filterCategoryList),true)
            dismiss()

            SpmTrackHandler.addSingleTrackData(
                SkAntEntity(
                    event = TrackEvent.elementClick.value,
                    spmCnt = GTrackerAssistUtils.fetchElementValue(
                        SpmPageDef.BrandDetailPage,
                        SpmElementDef.SearchGoodsFilterDone
                    ),
                    params = mapOf("filterContent" to getFilterContent(filterCategoryList),
                    "lowPrice" to "${filterPriceInputBean.min}","highPrice" to "${filterPriceInputBean.max}")
                )
            )
        }

//        if(frontCategoryIds?.isNotEmpty()==true){
//            mBinding.btnDone.setBackgroundResource(R.color.sk_red600)
//            mBinding.btnDone.isEnabled=true
//        }

        //没有一级分类
        mBinding.llCategory.visibleOrGone(ifHavefilterCategory)
    }

    private fun changeTab(position:Int){
        mBinding.vpDialogFilter.setCurrentItem(position, false)
        mBinding.llCategory.setBackgroundResource(R.color.transparent)
        mBinding.llPrice.setBackgroundResource(R.color.transparent)
        when(position){
            0->mBinding.llCategory.setBackgroundResource(R.color.white)
            1->mBinding.llPrice.setBackgroundResource(R.color.white)
        }
    }

    //改变按钮状态
    override fun changeBtnStates() {
//        val filterPriceInputBean=filterPriceFragment.getPriceInput()
//        val filterCategoryList=filterCategoryFragment.getFilterCategoryList()
//        if(filterPriceInputBean.min!=null||filterPriceInputBean.max!=null||filterCategoryList.isNotEmpty()){
//            mBinding.btnDone.setBackgroundResource(R.color.sk_red600)
//            mBinding.btnDone.isEnabled=true
//        }else{
//            mBinding.btnDone.setBackgroundResource(R.color.sk_red600_opacity50)
//            mBinding.btnDone.isEnabled=false
//        }
    }

    //获取筛选后的一级类目id 多个以逗号隔开
    private fun getFilterCategoryId(filterCategoryList: List<FilterCategoryBean>):ArrayList<String>?{
        if(filterCategoryList.isEmpty()){
            return null
        }
        val frontCategoryIds=ArrayList<String>()
        frontCategoryIds.addAll(filterCategoryList.map { it.categoryF?.id.toString() })
        return frontCategoryIds
    }

    //埋点使用获取筛选内容
    private fun getFilterContent(filterCategoryList: List<FilterCategoryBean>):String{
        val builder = StringBuilder()
        if(filterCategoryList.isNotEmpty()){
            filterCategoryList.forEach {
                builder.append("${it.categoryF?.name},")
            }
        }
        return builder.toString()
    }

    override fun changeRedPointState(){
        mBinding.tvCategory.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
        mBinding.tvPrice.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
        if(pageChangeSelected==0){
            //分类tab
            val filterPriceInputBean=filterPriceFragment.getPriceInput()
            if(filterPriceInputBean.min!=null||filterPriceInputBean.max!=null){
                mBinding.tvPrice.setCompoundDrawablesWithIntrinsicBounds(
                    redCircleDrawable,
                    null,
                    null,
                    null
                )
            }
        }else{
            //价格tab
            val filterCategoryList=filterCategoryFragment.getFilterCategoryList()
            if(filterCategoryList.isNotEmpty()) {
                mBinding.tvCategory.setCompoundDrawablesWithIntrinsicBounds(
                    redCircleDrawable,
                    null,
                    null,
                    null
                )
            }
        }
    }

    override fun hiddenCategoryFragment() {
        changeTab(1)
        mBinding.llCategory.visibleOrGone(false)
    }
}

interface FilterDialogI{
    fun changeBtnStates() //按钮状态修改
    fun changeRedPointState()//修改红点状态

    fun hiddenCategoryFragment()//没有品牌分类时隐藏品牌筛选
}